from flask import g, redirect, render_template, abort, request, jsonify, current_app

from info import db
from info.constants import QINIU_DOMIN_PREFIX, USER_COLLECTION_MAX_NEWS, USER_FOLLOWED_MAX_COUNT
from info.models import User, Category, News
from info.modules.user import user_blu
from info.utils.common import user_login_data
from info.utils.img_storage import upload_img
from info.utils.response_code import RET, error_map


@user_blu.route('/user_info')
@user_login_data
def user_info():

    user = g.user  #type:User
    # 判断用户是否登陆
    if not user:
        return redirect("/")

    return render_template("news/user.html",user=user.to_dict())
# 修改基本资料
@user_blu.route('/base_info',methods=["GET","POST"])
@user_login_data
def base_info():
    user = g.user  # type:User
    # 判断用户是否登陆
    if not user:
        abort(404)
    if request.method == "GET":
        return render_template("news/user_base_info.html",user=user.to_dict())

    # 获取参数
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")

    if gender not in ["MAN","WOMAN"]:
        jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    # 修改
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

# 修改头像
@user_blu.route('/pic_info',methods=["GET","POST"])
@user_login_data
def pic_info():
    user = g.user  # type:User
    # 判断用户是否登陆
    if not user:
        return redirect("/")
    # get查看头像页面
    if request.method == "GET":

        return render_template("news/user_pic_info.html", user=user.to_dict())
    # 改头像
    try:
        img_bytes = request.files.get("avatar").read()
    except BaseException as  e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    # 七牛云
    try:
        key = upload_img(img_bytes)
    except BaseException as  e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg=error_map[RET.THIRDERR])
    #保存头像
    user.avatar_url = key
                                                        #        七牛云路径和自己图片路径
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK],data={"avatar_url":QINIU_DOMIN_PREFIX + key})

# 修改密码
@user_blu.route('/pass_info',methods=["GET","POST"])
@user_login_data
def pass_info():
    user = g.user  # type:User
    # 判断用户是否登陆
    if not user:
        abort(404)
    if request.method == "GET":
        return render_template("news/user_pass_info.html",user=user.to_dict())

    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    #检查旧密码输入是否正确
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR,errmsg=error_map[RET.PWDERR])

    user.password = new_password

    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

#我的收藏
@user_blu.route('/collection')
@user_login_data
def collection():
    user = g.user  # type:User
    # 判断用户是否登陆
    if not user:
        abort(404)
    # 传过来的页数,默认第一页
    page = request.args.get("p", 1)
    # 转换
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    total_pages = 1
    try:
        # 查询出新闻,按页分,每页十个
        pn = user.collection_news.paginate(page, USER_COLLECTION_MAX_NEWS)
        news_list = [new.to_dict() for new in pn.items]
        total_pages = pn.pages
    except BaseException as e:
        current_app.logger.error(e)

    data={
        "news_list":news_list,
        "cur_page":page,
        "total_page":total_pages
    }

    return render_template("news/user_collection.html",data=data)

#新闻发布
@user_blu.route('/news_release',methods=["GET","POST"])
@user_login_data
def news_release():
    user = g.user  # type:User
    # 判断用户是否登陆
    if not user:
        abort(404)
    categories = []
    if request.method=="GET":
        try:
            # 查询出所有分类
            categories = Category.query.all()
        except BaseException as e:
            current_app.logger.error(e)

        if len(categories):
            categories.pop(0)
        return render_template("news/user_news_release.html",categories=categories)
    # 获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_img_file = request.files.get("index_image")
    content = request.form.get("content")
    if not all([title,category_id,digest,index_img_file,content]):
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    # 转换类型
    try:
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    # 上传图片文件到七牛
    try:
        img_bytes = index_img_file.read()
        key = upload_img(img_bytes)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg=error_map[RET.THIRDERR])
    # 创建新闻模型
    news = News()

    news.title = title
    news.category_id = category_id
    news.content = content
    news.digest = digest
    news.user_id = user.id
    news.index_image_url = QINIU_DOMIN_PREFIX + key
    news.source = user.nick_name
    # 发布状态
    news.status = 1 #默认审核中
    db.session.add(news)

    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

#我的新闻发布列表
@user_blu.route('/news_list')
@user_login_data
def news_list():
    user = g.user  # type:User
    # 判断用户是否登陆
    if not user:
        abort(404)
    # 传过来的页数,默认第一页
    page = request.args.get("p", 1)
    # 转换
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    total_pages = 1
    try:
        # 查询出新闻,按页分,每页十个
        pn = News.query.filter(News.user_id==user.id).paginate(page, USER_COLLECTION_MAX_NEWS)
        news_list = [news.to_review_dict() for news in pn.items]
        total_pages = pn.pages
    except BaseException as e:
        current_app.logger.error(e)

    data={
        "news_list":news_list,
        "cur_page":page,
        "total_page":total_pages
    }

    return render_template("news/user_news_list.html",data=data)


#我的关注
@user_blu.route('/user_follow')
@user_login_data
def user_follow():
    # 判断用户
    user = g.user #type:User
    if not user:
        abort(404)

    # 获取参数
    page = request.args.get("p",1)
    # 校验参数
    if not page:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1
    # 查询显示
    followed_list = []
    total_page = 1
    try:
        pn = user.followed.paginate(page, USER_FOLLOWED_MAX_COUNT)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])

    followed_list=[user.to_dict() for user in pn.items]
    total_page = pn.pages

    data = {
        "cur_page":page,
        "total_page":total_page,
        "followed":followed_list
    }

    return render_template("news/user_follow.html",data=data)


#个人主页
@user_blu.route('/other')
@user_login_data
def other():

    # 获取参数
    user_id = request.args.get("user_id")

    # 校验参数
    try:
        user_id = int(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)

    # 查询作者
    try:
        author = User.query.get(user_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(404)

    if not author:
        return abort(404)

    # 判断用户是否关注作者
    user = g.user
    is_follow = False
    if user:

        if author in user.followed:

            is_follow = True

    # 获取参数
    page = request.args.get("p", 1)

    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)

    # 查询新闻
    news_list = []
    total_page = 1
    try:
        pn = News.query.filter(News.user_id == author.id, News.status == 0).paginate(page, USER_COLLECTION_MAX_NEWS)
        news_list = [news.to_review_dict() for news in pn.items]
        total_page = pn.pages
    except BaseException as e:
        current_app.logger.error(e)


    data ={
        "news_list":news_list,
        "cur_page":page,
        "total_page":total_page
    }
    user = g.user.to_dict() if g.user else None

    return render_template("news/other.html",data=data,user=user,author=author.to_dict(),is_follow=is_follow)